import router from '@/router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const instance = axios.create({
  baseURL: 'http://localhost:8888/api/private/v1/'
})

// 拦截器
instance.interceptors.request.use(config => {
  if (config.url !== 'login') {
    const token = window.sessionStorage.getItem('token')
    config.headers.Authorization = token
  }
  return config
})

instance.interceptors.response.use(res => {
  if (res.data.meta.status === 401) {
    ElMessage({
      showClose: true,
      message: '登录过期，请重新登录！',
      type: 'error'
    })
    router.push('/login')
    return {}
  }
  return res.data
})

export default instance
